package wangwenjun.phase2.concurrencypattern.balking;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import util.ThreadUtil;

import java.io.IOException;
import java.util.Scanner;

/**
 * @author ChangLiang
 * @date 2020/6/16
 */
@Slf4j
public class DocumentEditThread extends Thread {

    /**
     * 主动进行文档编辑的线程
     */

    private final String documentPath;

    private final String documentName;

    private final Scanner scanner = new Scanner(System.in);

    public DocumentEditThread(String documentPath, String documentName) {
        super("document-edit-thread");
        this.documentName = documentName;
        this.documentPath = documentPath;
    }

    @Override
    public void run() {
        int times = 0;

        try {
            Document document = Document.create(documentPath, documentName);
            while (true) {
                String text = scanner.next();
                if (StringUtils.equals("quit", text)) {
                    document.close();
                    break;
                }
                document.edit(text);
                if (times == 5) {
                    document.save();
                    times = 0;
                }
                times++;
            }
        } catch (IOException e) {
            log.error(ThreadUtil.exceptionToString(e));
            throw new RuntimeException();
        }
    }
}
